#pragma once

#include <vector>
#include <thread>
#include <memory>
#include <queue>
#include <mutex>
#include <unistd.h>
#include <sys/eventfd.h>
#include "include/TcpSocket.hpp"
#include "include/Log.hpp"
#include "Common.hpp"
#include "ConnectionFactory.hpp"
#include "EventHandler.hpp"

static const int default_thread_num = 3;

class SubReactors
{
public:
    SubReactors(int efd, std::mutex* mtx, std::queue<int>* eventQueue, int threadNum = default_thread_num)
    {
        for(int i = 0; i < threadNum; i++)
        {
            _threads.emplace_back(std::thread(threadRoutine, efd, mtx, eventQueue));
            log.message(INFO, "createReactorThread, id: %d", i);
        }
    }
    
    ~SubReactors()
    {}
private:
    static void threadRoutine(int efd, std::mutex* mtx, std::queue<int>* eventQueue)
    {
        std::unique_ptr<Reactor> reactor = std::make_unique<Reactor>(efd, mtx, eventQueue);
        reactor->addConnection(ConnectionFactory::createEventConnection(
            efd, std::bind(&EventHandler::acceptForSelf, std::placeholders::_1), EPOLLIN|EPOLLET, reactor.get())); // 把efd伪装成tcp连接
        reactor->start();
    }
private:
    std::vector<std::thread> _threads;
};